import { messages } from 'share/common';
/**
 *  created by jsq on 2017/9/20
 */
import React from 'react';
import { connect } from 'react-redux';
import budgetService from 'containers/budget-setting/budget-organization/budget-structure/budget-structure.service';
import menuRoute from 'routes/menuRoute';
import debounce from 'lodash.debounce';
import { Badge, Button, Checkbox, Form, Icon, message, Popover, Row, Table, Tabs } from 'antd';
import 'styles/budget-setting/budget-organization/budget-structure/budget-structure-detail.scss';
import SlideFrame from 'components/slide-frame';
import NewDimension from 'containers/budget-setting/budget-organization/budget-structure/new-dimension';
import UpdateDimension from 'containers/budget-setting/budget-organization/budget-structure/update-dimension';
import ListSelector from 'components/list-selector';
import BasicInfo from 'components/basic-info';
import LanguageInput from 'components/template/language-input/language-input';

const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
let periodStrategy = [];

class BudgetStructureDetail extends React.Component{

  constructor(props){
    super(props);

    this.state = {
      loading: true,
      //添加公司弹框
      lov: {
        type: 'company_structure', //lov类型
        visible: false,  //控制是否弹出

      },
      updateState: false,
      structure:{},
      dimension: {},
      showSlideFrame: false,
      showSlideFrameUpdate: false,
      statusCode: messages('common.status.enable') /*启用*/,
      total:0,
      data:[],
      pagination: {
        current: 1,
        page: 0,
        total:0,
        pageSize:10,
        showSizeChanger:true,
        showQuickJumper:true,
      },
      label:"",
      columns:[],
      infoList: [
        {type: 'input', id: 'organizationName',isRequired: true, disabled: true, label: messages('budget-setting.key47'/*预算组织*/)+" :" /*预算组织*/},
        {type: 'input', id: 'structureCode',isRequired: true, disabled: true, label: messages('budget-setting.key105'/*预算表代码*/)+" :" /*预算表代码*/},
        {type: 'select',options: periodStrategy , isRequired: true, id: 'periodStrategy', label: messages('budget-setting.key185'/*编制期段*/) +" :"/*编制期段*/},
        {type: 'switch', id: 'isEnabled', label: messages('common.column.status') +" :"/*状态*/},
      ],
      extraInfo: [
        {
          type: 'input',
          id: 'structureName',
          isRequired: true,
          label: messages('budget-setting.key184'/*预算表名称*/) + ' :'/*预算表名称*/
        },
        {
          type: 'input',
          id: 'description',
          label: messages('budget-setting.key186'/*备注*/) + ' :'/*预算表描述*/
        }
      ],
      columnGroup:{
        company: [
          {                        /*公司代码*/
            title:messages('budget-setting.key56'/*公司代码*/), key: "companyCode", dataIndex: 'companyCode'
          },
          {                        /*公司名称*/
            title:messages('budget-setting.key57'/*公司名称*/), key: "companyName", dataIndex: 'companyName'
          },

          {                        /*启用*/
            title:messages('budget-setting.key187'/*启用*/), key: "doneRegisterLead", dataIndex: 'doneRegisterLead',width:'10%',
            render: (isEnabled, record) => <Checkbox onChange={(e) => this.onChangeEnabled(e, record)} checked={record.isEnabled}/>
          },
        ],
        dimension: [
          {                        /*成本中心编码*/
            title:messages('budget-setting.key221')/*成本中心编码*/, key: "dimensionCode", dataIndex: 'dimensionCode'
          },
          {                        /*维度名称*/
            title:messages('budget-setting.key222')/*成本中心名称*/, key: "dimensionName", dataIndex: 'dimensionName',
            render: record => (
              <span>{record ? <Popover content={record} overlayStyle={{maxWidth: 500}}>{record} </Popover> : '-'} </span>)
          },
          {                        /*布局位置*/
            title:messages('budget-setting.key190'/*布局位置*/), key: "layoutPositionName", dataIndex: 'layoutPositionName'
          },
          {                        /*布局顺序*/
            title:messages('budget-setting.key191'/*布局顺序*/), key: "layoutPriority", dataIndex: 'layoutPriority'
          },
          {                        /*默认维值代码*/
            title:messages('budget-setting.key223')/*默认成本中心项编码*/, key: "defaultDimValueCode", dataIndex: 'defaultDimValueCode',
            render:recode=> <span>{recode ? recode : '-'}</span>
          },
          {                        /*默认维值名称*/
            title:messages('budget-setting.key224')/*默认成本中心项名称*/, key: "defaultDimValueName", dataIndex: 'defaultDimValueName',
            render: record => (
              <span>{record ? <Popover content={record} overlayStyle={{maxWidth: 500}}>{record} </Popover> : '-'} </span>)
          },
          {title: messages('common.column.status'), dataIndex: 'isEnabled', width: '15%',
            render: isEnabled => (
              <Badge status={isEnabled ? 'success' : 'error'}
                     text={isEnabled ? messages('common.status.enable') : messages('common.disabled')} />
            )}, //状态
        ]
      },
      tabs: [
        {key: 'dimension', name: messages('budget-setting.key225')/*成本中心分配*/},
        {key: 'company', name: messages('budget-setting.key104'/*公司分配*/)}  /*公司分配*/
      ],
      i18n: {}
    };
    this.search = debounce(this.search,1000)
  }
  //改变启用状态
  onChangeEnabled = (e, record) => {
    this.setState({loading: true});
    record.isEnabled = e.target.checked;
    budgetService.updateStructureAssignCompany(record).then(() => {
      this.getList()
    })
  };

  componentWillMount(){

    //获取编制期段
    this.getSystemValueList(2002).then((response)=>{
      response.data.values.map((item)=>{
        let options = {
          label:item.messageKey, value:item.code
        };
        periodStrategy.addIfNotExist(options)
      });
    });

    //获取某预算表某行的数据
    budgetService.getStructureById(this.props.params.structureId).then((response)=> {
      response.data.periodStrategy = {
        label: response.data.periodStrategyName,
        value: response.data.periodStrategy
      };
      if(response.status === 200){
        const { i18n = {}, description, structureName } = response.data;
        this.setState({
          columns: this.state.columnGroup.dimension,
          structure: response.data,
          i18n,
          description,
          structureName
        });
        let infoList = this.state.infoList;
        infoList[2].disabled = response.data.usedFlag;
      }
    });
    this.getList();
  }

  //保存所做的修改
  handleUpdate = (value) => {
    console.log(value);
    let { structure: { id, versionNumber, organizationId }, i18n, description, structureName } = this.state;
    budgetService.updateStructures({
      ...value,
      ...{
        id,
        versionNumber,
        organizationId,
        i18n,
        structureName,
        description
      }
    })
      .then((response) => {
        if (response.status === 200) {
          let structure = response.data;
          structure.organizationName = this.state.structure.organizationName;
          message.success(messages('budget-setting.key31'/*保存成功！*/)); /*保存成功！*/
          structure.periodStrategy = {
            label: response.data.periodStrategyName,
            value: response.data.periodStrategy
          };
          this.setState({ structure: structure, updateState: true }, this.getList);
        }
      })
      .catch((e) => {
        if (e.response) {
          message.error(`${messages('common.operate.filed')}, ${e.response.data.message}`);
        }
      });
  };

  renderTabs(){
    return (
      this.state.tabs.map(tab => {
        return <TabPane tab={tab.name} key={tab.key}/>
      })
    )
  }

  //Tabs点击
  onChangeTabs = (key) => {
    let columnGroup = this.state.columnGroup;
    let pagination = this.state.pagination
    pagination.page = 0;
    pagination.pageSize = 10;
    this.setState({
      loading: true,
      pagination,
      data: [],
      label: key,
      columns: key === 'company' ? columnGroup.company : columnGroup.dimension
    },()=>{
      this.getList()
    });
  };

  //输入条件时的查询
  handleSearch = (e) =>{
    this.search(e.target.value)
  };

  search = (value)=>{
    this.setState({
      params:value
    })
  };

  handleCreate = (e) =>{
    this.state.label ==="company" ? this.showListSelector(true) : this.showSlide(true)
  };

  getList = ()=>{
    const { pagination } = this.state;
    let params = {
      structureId: this.props.params.structureId,
      page: pagination.page,
      size: pagination.pageSize
    };
    if(this.state.label === "company"){
      budgetService.getCompanyAssignedStructure(params).then((response)=>{
        if(response.status === 200) {
          response.data.map((item)=>{
            item.key = item.id
          });
          let pagination = this.state.pagination;
          pagination.total = Number(response.headers['x-total-count']);
          this.setState({
            loading: false,
            data: response.data,
            pagination,
            updateState: false
          })
        }
      })
    }else {
      budgetService.getDimensionAssignedStructure(params).then((response)=>{
        if(response.status === 200){
          response.data.map((item)=>{
            item.key = item.id
          });
          let pagination = this.state.pagination;
          pagination.total = Number(response.headers['x-total-count']);
          this.setState({
            loading: false,
            data: response.data,
            pagination,
            updateState: false
          })
        }
      })
    }
  };


  //控制新建维度侧滑
  showSlide = (flag) => {
    this.setState({
      showSlideFrame: flag
    })
  };

  //处理关闭新建侧滑维度页面
  handleCloseSlide = (params) => {
    this.setState({
      showSlideFrame: false,
      loading: typeof params !== 'undefined'
    });
    if(params) {
      this.getList();
    }
  };

  //点击行，进入维度编辑页面
  handleRowClick = (record, index, event) =>{
    if(this.state.label !== 'company'){
      let defaultDimensionCode = [];
      let defaultDimensionValue = [];
      defaultDimensionCode.push({ dimensionId: record.dimensionId, dimensionCode: record.dimensionCode,key: record.dimensionId});
      if (record.defaultDimValueId) {
        defaultDimensionValue.push({
          defaultDimValueId: record.defaultDimValueId,
          defaultDimValueCode: record.defaultDimValueCode,
          key: record.defaultDimValueId
        });
      }
      record.usedFlag = this.state.structure.usedFlag;
      record.defaultDimensionCode = defaultDimensionCode;
      record.defaultDimensionValue = defaultDimensionValue;
      this.setState({
        showSlideFrameUpdate: true,
        dimension:record
      })
    }
  };

  showSlideUpdate = (flag)=>{
    this.setState({
      showSlideFrameUpdate: flag
    })
  };

  //关闭新建侧滑维度页面
  handleCloseSlideUpdate = (params) => {
    this.setState({
      showSlideFrameUpdate: false,
      loading: typeof params !== 'undefined'
    });
    if(params) {
      this.getList();
    }
  };

  //控制是否弹出公司列表
  showListSelector = (flag) =>{
    let lov = this.state.lov;
    lov.visible = flag;
    this.setState({lov})
  };

  //处理公司弹框点击ok,分配公司
  handleListOk = (result) => {
    let company = [];
    result.result.map((item)=>{
      company.push({companyCode: item.code,companyId:item.id,structureId:this.props.params.structureId,isEnabled:item.isEnabled})
    });
    budgetService.structureAssignCompany(company).then((response)=>{
      if(response.status === 200) {
        this.showListSelector(false);
        this.setState({
            data: response.data,
          },
          this.getList()
        );
      }
    }).catch((e)=>{
      if(e.response){
        message.error(`${messages('common.operate.filed')}, ${e.response.data.message}`);
      }
      this.setState({loading: false});
    });
  };

  //返回预算表页面
  handleBack = () => {
    this.context.router.push(menuRoute.getMenuItemByAttr('budget-organization', 'key').children.budgetOrganizationDetail.url.replace(':id', this.props.params.id)+ '?tab=STRUCTURE');
  };

  //分页点击
  onChangePager = (pagination,filters, sorter) =>{
    let temp = this.state.pagination;
    temp.page = pagination.current-1;
    temp.current = pagination.current;
    temp.pageSize = pagination.pageSize;
    this.setState({
      loading: true,
      pagination: temp
    }, ()=>{
      this.getList();
    })
  };

  handleI18n = (name, value, tag) => {
    let { i18n, structureName, description } = this.state;
    if (tag === 'input') {
      i18n.structureName = value;
      structureName = name;
    } else {
      i18n.description = value;
      description = name;
    }
    this.setState({ structureName, description, i18n });
  };
  renderExtraFields = () => {
    const { i18n, extraInfo } = this.state;
    const { form: { getFieldDecorator } } = this.props;
    return extraInfo.map(item =>
      <FormItem label={item.label}>
        {getFieldDecorator(item.id, {
          initialValue: this.state[item.id],
          rules: [{
            required: item.isRequired,
            message: messages('common.can.not.be.empty', { name: item.label }),  //name 不可为空
          }]
        })(
          <LanguageInput
            key={item.id}
            isEdit={true}
            i18nName={i18n[item.id] || null}
            nameChange={(name, value) => this.handleI18n(name, value, item.id === 'structureName' ? 'input' : 'textArea')}
            placeholder={messages('common.please.enter')/* 请输入 */}
            mainLanguageIsRequired={!!item.isRequired}/>
        )}
      </FormItem>
    );
  };


  render(){
    const { infoList, dimension, updateState, structure, loading, showSlideFrameUpdate, data, columns, pagination, label, showSlideFrame, lov, extraInfo } = this.state;

    return(
      <div className="budget-structure-detail">
        <BasicInfo
          infoList={infoList}
          extraFields={this.renderExtraFields()}
          extraFieldsIndex={1}
          extraInfo={extraInfo}
          infoData={structure}
          updateHandle={this.handleUpdate}
          updateState={updateState}/>
        <div className="structure-detail-distribution">
          <Tabs onChange={this.onChangeTabs}>
            {this.renderTabs()}
          </Tabs>
        </div>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total: pagination.total})}</div>  {/*共搜索到*条数据*/}
          <div className="table-header-buttons">
            <Button type="primary"
                    disabled={label === 'company' ? false : structure.usedFlag}
                    onClick={this.handleCreate}>
              {label === 'company'? messages('budget-setting.key59'/*添加公司*/) : messages('common.create')}
            </Button>
          </div>
        </div>
        <Table
          dataSource={data}
          columns={columns}
          loading={loading}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          onChange={this.onChangePager}
          pagination={pagination}
          size="middle"
          bordered/>
        <a style={{fontSize:'14px',paddingBottom:'20px'}} onClick={this.handleBack}><Icon type="rollback" style={{marginRight:'5px'}}/>{messages('common.back')}</a>

        <SlideFrame title={messages('budget-setting.key195'/*新建维度*/)}
                    show={showSlideFrame}
                    content={NewDimension}
                    afterClose={this.handleCloseSlide}
                    onClose={() => this.showSlide(false)}
                    params={structure}/>
        <SlideFrame title={messages('budget-setting.key196'/*编辑维度*/)}
                    show={showSlideFrameUpdate}
                    content={UpdateDimension}
                    afterClose={this.handleCloseSlideUpdate}
                    onClose={() => this.showSlideUpdate(false)}
                    params={dimension}/>

        <ListSelector type={lov.type}
                      visible={lov.visible}
                      extraParams={{"structureId": structure.id}}
                      onOk={this.handleListOk}
                      onCancel={()=>this.showListSelector(false)}/>
      </div>
    )
  }

}
BudgetStructureDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization
  }
}

const WrappedBudgetStructureDetail = Form.create()(BudgetStructureDetail);

export default connect(mapStateToProps)(WrappedBudgetStructureDetail);
